﻿using System.ComponentModel;
using System.Windows.Data;
using MVVMtutorialAdvanced.Web;
using Riba.MVVMSL;

namespace MVVMtutorialAdvanced
{
	public class BookAuthors_VM : ViewModelBase
	{
		private readonly DomainServices.IDomainServiceBook _domainService;
		public RelayCommand CommandOk { get; private set; }

		private PagedCollectionView _entityList;
		public PagedCollectionView EntityList
		{
			get { return _entityList; }
			set { SetPropertyValue(ref _entityList, value, () => EntityList); }
		}

		private AuthorDTO _selectedEntity;
		public AuthorDTO SelectedEntity
		{
			get { return _selectedEntity; }
			set { SetPropertyValue(ref _selectedEntity, value, () => SelectedEntity); }
		}

		public BookAuthors_VM(DomainServices.IDomainServiceBook domainService)
		{
			_domainService = domainService;
			CommandOk = new RelayCommand(OnCommandOk);

			_domainService.GetAuthors
				(
					(data, error) =>
					{
						if (error != null)
						{
							RaiseShowMsgBox(new ShowMsgBoxEventArgs(error.Message, "Fehler"));
							return;
						}

						var pagedCollectionView = new PagedCollectionView(data);
						pagedCollectionView.SortDescriptions.Add(
							new SortDescription("LastName", ListSortDirection.Ascending));

						EntityList = pagedCollectionView;

						if (EntityList.Count > 0)
							SelectedEntity = EntityList[0] as AuthorDTO;

						CommandOk.IsEnabled = true;
					}
				);
		}

		private void OnCommandOk(object handler)
		{
			if (Callback != null)
				Callback(this, SelectedEntity);

			RaiseCloseChildWindowView();
		}
	}
}
